package com.bootdo.wechat.service.impl;

import com.bootdo.wechat.common.CopyUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpUserService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import com.bootdo.wechat.dao.MpFansDao;
import com.bootdo.wechat.domain.MpFansDO;
import com.bootdo.wechat.service.MpFansService;



@Service
public class MpFansServiceImpl implements MpFansService {
	@Autowired
	private MpFansDao mpFansDao;
	
	@Override
	public MpFansDO get(String id){
		return mpFansDao.get(id);
	}
	
	@Override
	public List<MpFansDO> list(Map<String, Object> map){
		return mpFansDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return mpFansDao.count(map);
	}
	
	@Override
	public int pullFans(String id, List<String> openids, WxMpUserService userService){
		int failNum= 0;
		for (String openId:openids) {
			MpFansDO fansDO = mpFansDao.selectFansByOpenId(openId);
			if (fansDO!=null){
				if (fansDO.getSubscribe()==1){
					fansDO.setSubscribe(0);
					mpFansDao.update(fansDO);
				}
			}else {
				try {
					WxMpUser wxMpUser = userService.userInfo(openId);
					fansDO = CopyUtils.copyFans(wxMpUser);
					fansDO.setMpId(id);
				}catch (WxErrorException e){
					failNum+=1;
				}
				mpFansDao.save(fansDO);
			}
		}
		return failNum;
	}

	@Override
	public int save(MpFansDO mpFans){
		return mpFansDao.save(mpFans);
	}

	@Override
	public int update(MpFansDO mpFans){
		return mpFansDao.update(mpFans);
	}
	
	@Override
	public int remove(String id){
		return mpFansDao.remove(id);
	}
	
	@Override
	public int batchRemove(String[] ids){
		return mpFansDao.batchRemove(ids);
	}
	
}
